package com.java.gulimalltestssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author jl
 * Created on 2020/8/20
 */
@Controller
public class LoginController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("/userInfo")
    @ResponseBody
    public String userInfo(@RequestParam("token")String token) {
        return redisTemplate.opsForValue().get(token);
    }

    @GetMapping("/login.html")
    public String login(@RequestParam("redirect_url")String redirect_url, Model model
            , @CookieValue(value = "sso_token",required = false)String sso_token) {
        if (!StringUtils.isEmpty(sso_token)) {
            // 说明之前已经登录成功,跳转回之前的页面
            return "redirect:"+redirect_url+"?token="+sso_token;
        }
        model.addAttribute("redirect_url",redirect_url);
        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("username")String username, @RequestParam("password")String password,
                          @RequestParam(value = "redirect_url",required = false)String redirect_url,
                          HttpServletResponse response) {


        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
            // 账号密码验证通过,保存用户信息
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            redisTemplate.opsForValue().set(uuid,username,30, TimeUnit.MINUTES);
            // 在登录服务器保存用户登录信息
            response.addCookie(new Cookie("sso_token",uuid));
            // 跳转回之前的页面
            return "redirect:"+redirect_url+"?token="+uuid;
        }
        return "login";

    }
}
